package yxy.game.pm2.command.soul;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.soulrefine;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Soul;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.hero.SoulHandle;

import java.util.Collection;

/** 魂玉 魂玉精炼 */
@MessageType(proto = Command.SoulRefine, classtype = HeroMessage.SoulRefineRequest.class)
public class CMD_SoulRefine extends Command<HeroMessage.SoulRefineRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.SoulRefineRequest request) {
		String playerCode = messageSource.getTag();
		String soulCode = request.getCode();

		HeroMessage.SoulRefineResponse.Builder response = HeroMessage.SoulRefineResponse.newBuilder();

		Soul soul = Soul.get(playerCode, soulCode);
		if (soul == null || soul.getHero() != null) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		// 扣费
		soulrefine _soulrefine = DataCenter.getAllData(soulrefine.class).values().iterator().next();
		try {
			Collection<Currency> cost = Currency.create(_soulrefine.getCosttype(), _soulrefine.getCostid(), _soulrefine.getCostnum());
			new CurrencyHandle().cost(playerCode, CCReason.魂玉, cost);
		} catch (CurrencyNotEnoughException e) {
			send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
			return;
		}
		boolean success = soul.refine(playerCode, _soulrefine);
		if (!success) {
			send(messageSource, response, Result.ParamError);
			return;
		}

		response.setSoul(new SoulHandle().packSoul(soul));
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, HeroMessage.SoulRefineResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}